package com.aps.apspda.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.aps.apspda.R;
import com.aps.apspda.base.BaseActivity;
import com.aps.apspda.callback.DialogEntityCallBack;
import com.aps.apspda.callback.EntityCallBack;
import com.aps.apspda.callback.StringCommonCallBack;
import com.aps.apspda.dialog.DeleteFragmentDialog;
import com.aps.apspda.dialog.WarnFragmentDialog;
import com.aps.apspda.entity.BaseEntity;
import com.aps.apspda.entity.ChildEqpEntity;
import com.aps.apspda.entity.FinishLotEntity;
import com.aps.apspda.entity.LoginEntity;
import com.aps.apspda.entity.LotInfoEntity;
import com.aps.apspda.fragment.FunctionFragment;
import com.aps.apspda.myview.TitleView;
import com.aps.apspda.utils.AntiShake;
import com.aps.apspda.utils.NetUtils;
import com.aps.apspda.utils.StaticMembers;
import com.aps.apspda.utils.ToastUtils;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class ModeSelectActivity extends BaseActivity {
    @BindView(R.id.topViewrequest)  //标题按钮
            TitleView topViewrequest;
    @BindView(R.id.eqpIdResult)   //当前设备号
            TextView eqpIdResult;
    @BindView(R.id.tvLoggingrequest)  //正常模式按钮
            TextView tvLoggingrequest;
    @BindView(R.id.offlineModerequest)  //离线模式按钮
            TextView offlineModerequest;
    private String eqpid = "";
    private String eqptype="";
    private String  modeselect = ""; //判断当前是切正常模式还是离线模式，Y为离线模式，N为正常模式
    private List<ChildEqpEntity.EqpObject> childEqpList;
    private LotInfoEntity yueLotInfo, currentLotInfo;
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_modeselection;
    }

    @Override
    protected void initData() {
        eqpid = getIntent().getStringExtra("eqpID");
        eqptype = getIntent().getStringExtra("eqpType");
        requestGetEqpID(eqpid);
    }

    @Override
    protected void initView() {
        eqpIdResult.setText(getIntent().getStringExtra("eqpID"));
        topViewrequest.setTitle("模式选择(" + StaticMembers.CUR_USER.getUSERNAME() + ")");
 /*       if (modetype.equals("Y")) {
            topView.setTitle("批次开始(" + StaticMembers.CUR_USER.getUSERNAME() + ")离线模式");
            StaticMembers.isOffLine = true;
            llBladeExp.setVisibility(View.GONE);
        } else {
            StaticMembers.isOffLine = false;
            llBladeExp.setVisibility(View.GONE);
            topView.setTitle("批次开始(" + StaticMembers.CUR_USER.getUSERNAME() + ")正常模式");
        }*/
    }

    @OnClick({R.id.eqpIdResult, R.id.tvLoggingrequest, R.id.offlineModerequest})
    public void onClick(View view) {
        if (AntiShake.check(view.getId())) {    //判断是否多次点击
            ToastUtils.showFreeToast("请勿重复点击",
                    ModeSelectActivity.this, false, Toast.LENGTH_SHORT);
            return;
        }
        switch (view.getId()) {
            //正常模式
            case R.id.tvLoggingrequest:
                View view1 = LayoutInflater.from(ModeSelectActivity.this).inflate(R.layout.activity_jurisdiction, null);
                final AlertDialog buildepoxy = new AlertDialog.Builder(ModeSelectActivity.this)
                        .setView(view1)
                        .setPositiveButton("切换", null)
                        .setNegativeButton("取消", null)
                        .show();
                buildepoxy.setView(view1);
                final EditText usernam1e = (EditText) view1.findViewById(R.id.etMobile2request);
                final EditText passwprd = (EditText) view1.findViewById(R.id.etPassword2request);
                (buildepoxy).getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view1) {
                        if (usernam1e.getText().toString().trim().length() == 0) {
                            ToastUtils.showFreeToast("请输入用户名!", ModeSelectActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        } else if (passwprd.getText().toString().trim().length() == 0) {
                            ToastUtils.showFreeToast("请输入密码!", ModeSelectActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        } else {
                            modeselect = "N";
                            requestLogin(usernam1e.getText().toString().trim(), passwprd.getText().toString().trim());
                            buildepoxy.cancel();
                        }
                    }
                });
                (buildepoxy).getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view1) {
                        buildepoxy.cancel();
                    }
                });
                buildepoxy.show();
                break;
            //离线模式
            case R.id.offlineModerequest:
                View view2 = LayoutInflater.from(ModeSelectActivity.this).inflate(R.layout.activity_jurisdiction, null);
                final AlertDialog buildepoxy1 = new AlertDialog.Builder(ModeSelectActivity.this)
                        .setView(view2)
                        .setPositiveButton("切换", null)
                        .setNegativeButton("取消", null)
                        .show();
                buildepoxy1.setView(view2);
                final EditText usernam1e1 = (EditText) view2.findViewById(R.id.etMobile2request);
                final EditText passwprd1 = (EditText) view2.findViewById(R.id.etPassword2request);
                (buildepoxy1).getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view1) {
                        if (usernam1e1.getText().toString().trim().length() == 0) {
                            ToastUtils.showFreeToast("请输入用户名!", ModeSelectActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        } else if (passwprd1.getText().toString().trim().length() == 0) {
                            ToastUtils.showFreeToast("请输入密码!", ModeSelectActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        } else {
                            modeselect = "Y";
                            requestLogin(usernam1e1.getText().toString().trim(), passwprd1.getText().toString().trim());
                            buildepoxy1.cancel();
                        }
                    }
                });
                (buildepoxy1).getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view1) {
                        buildepoxy1.cancel();
                    }
                });
                buildepoxy1.show();
                break;
        }
    }
    private void requestLogin(String username, String passwprd) {
        EntityCallBack<BaseEntity<LoginEntity>> callBack = new DialogEntityCallBack<BaseEntity<LoginEntity>>
                (new TypeToken<BaseEntity<LoginEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<LoginEntity>> response) {
                if (response.body().isSuccess(ModeSelectActivity.this)) {
                    LoginEntity loginEntity = response.body().getData();
                    if (loginEntity.getLOGINRESULT()) {
                      /*  if (loginEntity.getISACTIVE()) {*/
                            //StaticMembers.CUR_USER = loginEntity;
                            ToastUtils.showFreeToast("权限验证成功!",
                                    ModeSelectActivity.this, true, Toast.LENGTH_SHORT);
                            //ModeSelectActivity.this.finish();
                            if("Y".equals(modeselect)){
                                String EQPModeType = "Y";
                                requestChange(eqpid,EQPModeType);
                            }else if("N".equals(modeselect)){
                                String EQPModeType = "N";
                                requestChange(eqpid,EQPModeType);
                            }else{
                                String EQPModeType ="";
                                requestChange(eqpid,EQPModeType);
                            }
/*                        } else {
                            ToastUtils.showFreeToast(loginEntity.getMESSAGE(),
                                    ModeSelectActivity.this, true, Toast.LENGTH_SHORT);
                        }*/
                    } else {
                        ToastUtils.showFreeToast(loginEntity.getMESSAGE(),
                                ModeSelectActivity.this, true, Toast.LENGTH_SHORT);
                    }
                } else {
                    loadFail(response.body().getMessage());
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<LoginEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "ClientLogin");
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("USERNAME", username);
        map.put("PASSWORD", passwprd);
        map.put("LOGGEDUSER", StaticMembers.CUR_USER.getUSERNAME());
        map.put("LOGINTYPE", "MODESELECT");
        NetUtils.requestNet(this, "/ClientLogin", map, callBack);
    }

    private void requestChange(String eqpid,String EQPModeType) {
        EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new DialogEntityCallBack<BaseEntity<FinishLotEntity>>
                (new TypeToken<BaseEntity<FinishLotEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<FinishLotEntity>> response) {
                if (response.body().isSuccess(ModeSelectActivity.this)) {
                    Message message = new Message();
                    message.what = 0;
                /*    handler.sendMessage(message);*/
                    if (response != null && response.body() != null && response.body().getCode() == 200) {
                        response.body().setMessage("切换成功!");
                        loadSuccess(response.body().getMessage());
                        //startActivity(new Intent(ModeSelectActivity.this, FunctionFragment.class));
                        //startActivity(new Intent(ModeSelectActivity.this, HomeActivity.class));
                        ModeSelectActivity.this.finish();
                    /*    final DeleteFragmentDialog deleteFragmentDialog = new DeleteFragmentDialog();
                        ModeSelectActivity.this.finish();
                        deleteFragmentDialog.show(getSupportFragmentManager(), "unbind_dialog");*/
                    } else {
                        response.body().setMessage("切换失败!");
                        loadSuccess(response.body().getMessage());
                    }
                } else {
                    loadFail(response.body().getMessage());
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<FinishLotEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "ResultChangeEQPStatus");
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EQPID", eqpid);
        //map.put("USERNAME", StaticMembers.CUR_USER.getUSERNAME());
        map.put("EQPModeType", EQPModeType);
        NetUtils.requestNet(this, "/ResultChangeEQPStatus", map, callBack);
    }

    private void requestGetEqpID(String eqpid) {
        EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new DialogEntityCallBack<BaseEntity<FinishLotEntity>>
                (new TypeToken<BaseEntity<FinishLotEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<FinishLotEntity>> response) {
                if (response.body().isSuccess(ModeSelectActivity.this)) {
                    Message message = new Message();
                    message.what = 0;
                   /* *//*    handler.sendMessage(message);*//*
                    if (response != null && response.body() != null && response.body().getCode() == 200) {
                        response.body().setMessage("切换成功!");
                        loadSuccess(response.body().getMessage());
                        //startActivity(new Intent(ModeSelectActivity.this, FunctionFragment.class));
                        //startActivity(new Intent(ModeSelectActivity.this, HomeActivity.class));
                        ModeSelectActivity.this.finish();
                    *//*    final DeleteFragmentDialog deleteFragmentDialog = new DeleteFragmentDialog();
                        ModeSelectActivity.this.finish();
                        deleteFragmentDialog.show(getSupportFragmentManager(), "unbind_dialog");*//*
                    } else {
                        response.body().setMessage("切换失败!");
                        loadSuccess(response.body().getMessage());
                    }*/
                } else {
                    //loadFail();
                    //modify by bunny  fail后返回主界面
                    final WarnFragmentDialog dialog = new WarnFragmentDialog();
                    dialog.setData(response.body().getMessage());
                    dialog.setListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                            ModeSelectActivity.this.finish();
                        }
                    });
                    dialog.show(getSupportFragmentManager(), "check_fail_tips");
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<FinishLotEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "ShowReserveEQPInfoC2E");
                ModeSelectActivity.this.finish();
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EQPID", eqpid+"_ModeType");
        map.put("USERNAME", StaticMembers.CUR_USER.getUSERNAME());
        NetUtils.requestNet(this, "/ShowReserveEQPInfoC2E", map, callBack);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }
}
